import datetime
from typing import List, Optional
from pydantic import BaseModel, Field, validator
from schemas import _validator


class QuestionnaireBase(BaseModel):
    accesstoken: Optional[str]
    name: str
    start_time: str
    end_time: str
    img_path: List[str]
    desc: str

    answer_time: int


class QuestionnaireCreate(QuestionnaireBase):
    areacode: str = Field(..., alias="area_id")
    create_time: str = datetime.datetime.now().strftime("%Y-%m-%d %X")
    # 转json
    container_json_encode = validator(
        "img_path", allow_reuse=True)(_validator.container_json_encode)

    class Config:
        schema_extra = {
            "example": {
                          "accesstoken": "TOKEN3590",
                          "name": "小区调查问卷",
                          "desc": "小区业主们对加装电梯的意见",
                          "start_time": "2022-03-10 08:00:00",
                          "end_time": "2022-03-15 08:30:00",
                          "area_id": 1500,
                          "answer_time": 120,
                          "template_id": 1296,
                          "img_path": [
                            "http://slave.homed.me/1.jpg",
                            "http://slave.homed.me/2.jpg"
                          ]
                        }
        }


class QuestionnaireAdjust(QuestionnaireCreate):
    id: int

    class Config:
        schema_extra = {
            "example": {
                          "id": 1,
                          "accesstoken": "TOKEN3590",
                          "name": "小区调查问卷",
                          "desc": "小区业主们对加装电梯的意见",
                          "start_time": "2022-03-10 08:00:00",
                          "end_time": "2022-03-15 08:30:00",
                          "area_id": 1500,
                          "answer_time": 120,
                          "template_id": 1296,
                          "img_path": [
                            "http://slave.homed.me/1.jpg",
                            "http://slave.homed.me/2.jpg"
                          ]
                        }
        }


class QuestionnaireDelete(BaseModel):
    id: List[int]


class Questionnaire(QuestionnaireBase):
    id: int
    create_time: str
    area_id: str = Field(..., alias="areacode")
    # 转 dict
    container_json_decode = validator("img_path", pre=True, allow_reuse=True)(_validator.container_json_decode)
    # datetime 转换
    datetime_str_decode = validator(
        "start_time", "end_time", "create_time", pre=True, allow_reuse=True)(
        _validator.datetime_str_decode)

    class Config:
        orm_mode = True


if __name__ == '__main__':
    from sql_app.database import SessionLocal
    from sql_app.models import TActivityQuestionnaire

    db = SessionLocal()
    res = db.query(TActivityQuestionnaire).filter(TActivityQuestionnaire.id==1).scalar()
    res.name = "MERGE测试测试"
    db.merge(res)
    db.refresh(res)
    db.commit()
